#include "input.h"
#include "stm32f1xx_hal.h"

uint32_t upTime[3]={0,0,0};
uint32_t downTime[3]={0,0,0};
volatile uint32_t inputValue[3]={0,0,0};

static const uint32_t tim4_reload = 65535;
void tim4_init(void)
{	
	__HAL_RCC_AFIO_CLK_ENABLE();
	__HAL_RCC_TIM4_CLK_ENABLE();	
	
	TIM4->PSC = 72-1;
	TIM4->ARR = tim4_reload;		
	TIM4->CR1 |= 0x01;
}

void EXTI15_10_IRQHandler(void)
{	 
	if (__HAL_GPIO_EXTI_GET_IT(GPIO_PIN_12) != RESET)
	{
		if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_12)==GPIO_PIN_SET) 	{
			upTime[0] = TIM4->CNT;
		} else 	{
			downTime[0] = TIM4->CNT;
			
			if(downTime[0]>upTime[0]){
				inputValue[0] = downTime[0] - upTime[0];
			}else{
				inputValue[0] = downTime[0] + tim4_reload - upTime[0];
			}
		}
		__HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_12);		
	}
	
	if (__HAL_GPIO_EXTI_GET_IT(GPIO_PIN_13) != RESET)
	{
		if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_13)==GPIO_PIN_SET) 	{
			upTime[1] = TIM4->CNT;
		} else 	{
			downTime[1] = TIM4->CNT;
			
			if(downTime[1]>upTime[1]){
				inputValue[1] = downTime[1] - upTime[1];
			}else{
				inputValue[1] = downTime[1] + tim4_reload - upTime[1];
			}
		}
		__HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_13);		
	}
	
	if (__HAL_GPIO_EXTI_GET_IT(GPIO_PIN_14) != RESET)
	{
		if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_14)==GPIO_PIN_SET) 	{
			upTime[2] = TIM4->CNT;
		} else 	{
			downTime[2] = TIM4->CNT;
			
			if(downTime[2]>upTime[2]){
				inputValue[2] = downTime[2] - upTime[2];
			}else{
				inputValue[2] = downTime[2] + tim4_reload - upTime[2];
			}
		}
		__HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_14);		
	}
}

void input_init(void)
{
	GPIO_InitTypeDef GPIO_Initure; 	

	GPIO_Initure.Pin=GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_14;
    GPIO_Initure.Mode=GPIO_MODE_IT_RISING_FALLING;
	GPIO_Initure.Pull = GPIO_PULLUP;    
  	HAL_GPIO_Init(GPIOB, &GPIO_Initure);	
	
	HAL_NVIC_SetPriority(EXTI15_10_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(EXTI15_10_IRQn);
	
	tim4_init();
}


